

var map_user_data = {};
var map_shop_name = '';
var map_city_name = '';

function map_load(callback)
{
    var script = document.createElement("script");  
    script.src = "http://api.map.baidu.com/api?v=1.4";
    if (callback)
        script.src += "&callback=" + callback;

    document.body.appendChild(script);  
}  

function map_get_point(map, name, callback)
{
    var myGeo = new BMap.Geocoder();
    myGeo.getPoint(name, function(point) {
        if (point) {
            callback(point);
        }
    });
}

function map_add_label(map, class_name, name, text)
{
    map_get_point(map, name, function(point) {
        var marker = new BMap.Marker(point);

        if (typeof(text) != 'undefined') {
            var label_text = '<div style="width:auto;border-radius:5px;border:1px red solid;margin-left:-6px;display:inline;padding:6px;background-color:#fff;">' + text + '</div>';
            var label = new BMap.Label(label_text, { offset: new BMap.Size(0, -6) });
            marker.setLabel(label);
        }

        map_user_data_add(map, class_name, marker);
        map.addOverlay(marker);
    });
}

function map_add_shop(map, class_name, item)
{
    var marker = new BMap.Marker(new BMap.Point(item.Lng, item.Lat));
    var zoom = map.getZoom();

    var opts = {width : 350, height: 160, title : item.Name };

    var content = '';
    content += '<table style="margin-top:10px;width:100%;height:100px;"><tr><td width="100">';
    content += '<img src="../' + item.Logo +'" width="100" height="100" />';
    content += '</td><td align="left" style="float:left;margin-left:20px;">';
    content += '主营：' + item.Major + '<br />' ;
    content += '电话：' + item.Phone+ '<br />' ;
    content += '地址：' + item.BusinessAddress + '<br />' ;
    content += '</td></tr></table>';
    content += '<div style="float:right;margin-top:10px;"><a href="../shop/' + item.Id + '" style="color:#600;">查看详情 &gt;&gt;</a></div>' ;

    var infoWindow = new BMap.InfoWindow(content, opts);
    marker.addEventListener("click", function() {
        if (! infoWindow.isOpen())
            this.openInfoWindow(infoWindow);  
        else
            this.closeInfoWindow();
    });

//    if (zoom >= 11) {
        var label_text = '<div style="width:auto;border-radius:5px;border:1px red solid;margin-left:-6px;display:inline;padding:6px;background-color:#fff;">' + item.Name + '</div>';
        var label = new BMap.Label(label_text, { offset: new BMap.Size(16, -16) });

        marker.setLabel(label);
        label.addEventListener("click", function() {
            marker.openInfoWindow(infoWindow);  
        });
//    } else
//        label = null;

    map_user_data_add(map, class_name, marker);
    map.addOverlay(marker);
}

function map_draw_boundary(map, class_name, name, fill_color)
{
    var boundary = new BMap.Boundary();
    boundary.get(name, function(rs) { 
        for (var i = 0; i < rs.boundaries.length; i++) {
            var ply = new BMap.Polygon(rs.boundaries[i], {fillWeight: 2, fillColor: fill_color});
            map_user_data_add(map, class_name, ply);
            map.addOverlay(ply);
        }
    });  
}

function map_user_data_has(map, class_name)
{
    return map_user_data.hasOwnProperty(class_name);
}

function map_user_data_add(map, class_name, item)
{
    if (! map_user_data_has(map, class_name))
        map_user_data[class_name] = [];

    for (var i = 0 ; i < map_user_data[class_name].length ; i ++) {
        var x = map_user_data[class_name][i];
        if (x == item)
            return;
    }

    map_user_data[class_name].push(item);
}

function map_user_data_show(map, class_name)
{
    var user_data = map_user_data[class_name];
    if (! user_data)
        return;

    for (var i = 0 ; i < user_data.length ; i ++)
        map.addOverlay(user_data[i]);
}

function map_user_data_hide(map, class_name)
{
    var user_data = map_user_data[class_name];
    if (! user_data)
        return;

    for (var i = 0 ; i < user_data.length ; i ++)
        map.removeOverlay(user_data[i]);
}

function map_user_data_hide_all(map)
{
    for (var class_name in map_user_data) {
        if (class_name == 'shop_id')
            continue;

        var user_data = map_user_data[class_name];
        for (var i = 0 ; i < user_data.length ; i ++)
            map.removeOverlay(user_data[i]);

    }

    map_user_data['shop'] = [];
    map_user_data['shop_id'] = [];
}

function map_show_province(map)
{
    if (! map_user_data_has(map, 'province_boundary')) {
        map_ajax('get_province_info', null, function(list) {
            for (var i = 0 ; i < list.length ; i ++) {
                var item = list[i];

                map_draw_boundary(map, 'province_boundary', item.Name, 'red');
                map_add_label(map, 'province_label', item.Name, item.Name + ' 〡 ' + item.Count + '个商铺');
            }
        });
    } else {
        map_user_data_show(map, 'province_boundary');
        map_user_data_show(map, 'province_label');
    }
}

function map_show_city(map)
{
    if (! map_user_data_has(map, 'city_boundary')) {
        map_ajax('get_city_info', null, function(list) {
            for (var i = 0 ; i < list.length ; i ++) {
                var item = list[i];

                map_draw_boundary(map, 'city_boundary', item.Name, 'red');
                map_add_label(map, 'city_label', item.Name, item.Name + ' 〡 ' + item.Count + '个商铺');
            }
        });
    } else {
        map_user_data_show(map, 'city_boundary');
        map_user_data_show(map, 'city_label');
    }
}

function map_show_district(map)
{
    if (! map_user_data_has(map, 'district_boundary')) {
        map_ajax('get_district_info', null, function(list) {
            for (var i = 0 ; i < list.length ; i ++) {
                var item = list[i];

                map_draw_boundary(map, 'district_boundary', item.Name, 'red');
                map_add_label(map, 'district_label', item.Name, item.Name + ' 〡 ' + item.Count + '个商铺');
            }
        });
    } else {
        map_user_data_show(map, 'district_boundary');
        map_user_data_show(map, 'district_label');
    }
}

function map_show_shop(map, list)
{
    var new_list = [];

    if (! map_user_data_has(map, 'shop')) {
        map_user_data['shop_id'] = [];
        map_user_data['shop'] = [];
        new_list = list;
    } else {
        for (var i = 0 ; i < list.length ; i ++) {
            var j = 0;
            for ( ; j < map_user_data.shop_id.length ; j ++)
                if (map_user_data.shop_id[j] == list[i].Id)
                    break;

            if (j < map_user_data.shop_id.length) {
                continue;
            }

            new_list.push(list[i]);
        }
    }

    for (var i = 0 ; i < new_list.length ; i ++) {
        var item = new_list[i];

        map_add_shop(map, 'shop', item);
        map_user_data['shop_id'].push(item.Id);
    }
}

function map_show_all(map)
{
    var center = map.getCenter();
    var bounds = map.getBounds();
    var span = bounds.toSpan();

    var ratio = 0.5;
    var args = {
        lng: center.lng,
        lat: center.lat,
        lng_span: span.lng * ratio,
        lat_span: span.lat * ratio
    };

    map_ajax('get_all_info', args, function(list) {
        map_show_shop(map, list);
    });
}

function map_ajax(name, args, callback)
{
    if (! args)
        args = {};

    $.ajax({
        url: "../welcome/map_" + name,
        dataType: 'json',
        data: args,
        async: false,
        success: function(data) {
            if (data.status != 'success')
                return;

            callback(data.list);
        }
    });
}

function map_zoom_callback(map)
{
    var zoom = map.getZoom();

    map_user_data_hide_all(map);

    if (map_shop_name || map_city_name) {
        map_show_search_shop(map, map_shop_name, map_city_name);
        return;
    }

    switch (zoom) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            map_show_province(map);
            break;

        case 6:
        case 7:
        case 8:
            map_show_city(map);
            break;

        case 9:
        case 10:
        case 11:
            map_show_district(map);
            break;

        case 12:
            if (! map_user_data_has(map, 'district_boundary')) {
                map_ajax('get_district_info', null, function(list) {
                    for (var i = 0 ; i < list.length ; i ++) {
                        var item = list[i];

                        map_draw_boundary(map, 'district_boundary', item.Name, 'red');
                    }
                });
            } else {
                map_user_data_show(map, 'district_boundary');
            }

        default:
            map_show_all(map);
    }
}

function map_on_zoom(map)
{
    map.addEventListener("zoomend", function(e) {
        map_zoom_callback(map);
    });
}

function map_on_move(map)
{
    map.addEventListener("moveend", function(e) {
        if (map_shop_name != '' || map_city_name != '')
            return;

        var zoom = map.getZoom();
        if (zoom < 13)
            return;

        map_show_all(map);
    });
}

function map_search_shop(map, shop_name, city_name)
{
//    var re_center = (city_name != '' && city_name != map_city_name);

    map_shop_name = shop_name;
    map_city_name = city_name;

/*
    if (re_center)
        map.setCenter(city_name);
*/

    map.centerAndZoom(city_name, 9);

    map_zoom_callback(map);
}

function map_show_search_shop(map, shop_name, city_name)
{
    map_ajax('get_all_shops?name=' + shop_name + '&city=' + city_name, null, function(list) {
        map_draw_boundary(map, 'city_boundary', city_name, '');

        for (var i = 0 ; i < list.length ; i ++) {
            var item = list[i];

            if (item.Lng == null || item.Lng == '' || item.Lng == '0')
                continue;

            if (item.Lat == null || item.Lat == '' || item.Lat == '0')
                continue;

            map_add_shop(map, 'shop', item);
            map_user_data['shop_id'].push(item.Id);
        }
    });
}

function map_init(container)
{
    var map = new BMap.Map(container);  

    map.centerAndZoom("中国", 5);
    map.addControl(new BMap.NavigationControl());
    map.enableScrollWheelZoom();
    map.enableContinuousZoom();
    map.disableInertialDragging();
    map.disableDoubleClickZoom();
    // map.addControl(new BMap.ScaleControl());

    map_on_zoom(map);
    map_on_move(map);

    return map;
}
